<?php

namespace app\api\controller;

use app\api\model\Admin;
use think\Controller;
use think\exception\HttpResponseException;
use app\common\controller\Token;
use app\api\model\Permissions as PerModel;
use think\Db;
use think\Request;

class Login extends Controller
{
    public function responseJson($data = [],$code = 0)
    {
        $msg =  $GLOBALS['ERR_CODE'][$code] ? $GLOBALS['ERR_CODE'][$code] : '';
        throw new HttpResponseException(json(['code'=>$code,'msg'=> $msg,'data'=>$data]));
    }

    //登录
    public function login()
    {
        //判断请求方式是否正确
        if (Request::instance()->isPost()){
            $account  = Request::instance()->param('account',null);//获取用户账号
            $password = Request::instance()->param('password',null);//获取用户密码
            //判断账号密码是否符合要求
            if (empty($account)){
                $this->responseJson([],1002);
            }
            if (empty($password)){
                $this->responseJson([],1007);
            }
            $adminData = Admin::get(['account'=>$account]);
            //判断账号是否存在
                if (empty($adminData)){
                    $this->responseJson([],1013);
                }
                if (md5($password.$adminData['salt'].'$%$^%$&^%&') != $adminData['password']){
                    $this->responseJson([],1008);
                }
                $tmp = new Token();

            //获取该账号下的权限、
            $permissions = $this->obtain($account);
                $data = [
                    'token'   =>  $tmp->setToken($account),//token
                    'type'    =>  $adminData['type'],//属于那个类型
                    'id'      =>  $adminData['id'],
                    'name'    =>  $adminData['name'],
                    'permissions' => $permissions,//权限
                    'time'    => time(),
                ];
               $this->responseJson($data,0);
        }
        $this->responseJson([],1000);
    }

    //获取该管理员权限
    public function obtain($account)
    {
        //获取该用户角色
        $rid = Db::name('admin')->where('account',$account)->field('roles')->find();
        //判断角色是否存在
        $tmp = Db::name('roles')->where('id',$rid['roles'])->find();
        if (empty($tmp)){
            return false;
        }
        //获取该角色下的权限
        $permissions = Db::name('rolepermissions')->where('role_id',$tmp['id'])->find();
        if(empty($permissions)){
            return [];
        }
        $data = json_decode($permissions['permission_id'],true);
        $data = PerModel::all($data);
        if (empty($data)){
            return [];
        }
        foreach ($data as $key=>$val){
            $list[$key]['id'] = $val['id'];
            $list[$key]['title'] = $val['title'];
            $list[$key]['controller'] = $val['controller'];
        }
        return  $list;

    }
}
